package com.fsai.cms.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.fsai.cms.base.BaseResp;
import com.fsai.cms.base.WebCons;

/**
 * 500异常
 *
 * @project: sod-web-admin
 *
 * @author: JaffeHe
 * @email: JaffeHe@foxmail.com
 * @date: 2020-06-05 20:53
 *
 * @ChangeLog<br/>
 * 				Developer Date Comment <br/>
 */
@ControllerAdvice
public class Global500ExceptionHandler {

	protected Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 全局异常捕获
	 */
	@ExceptionHandler(Exception.class)
	public ModelAndView exceptionHandle(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		try {

			log.error("是否AJAX请求：" + this.isAjax(request) + "是否Admin:" + isAdmin(request) + "---系统发生了错误---"
					+ ex.getMessage(), ex);
			// 如果为异步请求，返回ApiResponse对象
			if (this.isAjax(request)) {
				response.setHeader("content-type", "text/html;charset=UTF-8");
				response.getWriter().write(JSON
						.toJSONString(BaseResp.holderResp(WebCons.SERVER_ERROR_CODE, ex.getMessage(), "不小心出了个错..")));
				return null;
			}
			// 跳转至error页面
			ModelMap model = new ModelMap();
			model.addAttribute("errorMsg", ex.getMessage());
			model.addAttribute("exception", ex);
			model.addAttribute("backIndex", isAdmin(request) ? "/admin/index" : "/");
			return new ModelAndView("public/pg500", model);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			ModelMap model = new ModelMap();
			model.addAttribute("errorMsg", "未知异常");
			model.addAttribute("exception", ex);
			model.addAttribute("backIndex", isAdmin(request) ? "/admin/index" : "/");
			return new ModelAndView("public/pg500", model);
		}
	}

	/**
	 * 判断请求是否为异步
	 */
	private boolean isAjax(HttpServletRequest request) {
		return StringUtils.isNotBlank(request.getHeader("X-Requested-With"));
	}

	/**
	 * 判断请求是否admin
	 */
	private boolean isAdmin(HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		return requestURI.contains("admin");
	}
}